<template>
  <el-card>
    <el-tabs v-model="activeTab">
      <!-- 待付款 -->
      <el-tab-pane label="待付款" name="pending">
        <el-skeleton v-if="loadingPending" animated />
        <div v-else-if="pendingOrders?.length === 0" class="empty-message">暂无待付款订单</div>
        <el-list
            v-for="order in pendingOrders"
            :key="order.orderNumber"
            class="order-item"
            v-else
        >
          <el-row>
            <el-col :span="18">
              <h3>{{ order.stationName }} {{ order.pileCode }}</h3>
              <p>订单号: {{ order.orderNumber }}</p>
              <p>充电状态: {{ order.chargingStatus }}</p>
            </el-col>
            <el-col :span="6" class="price">
              应付款: ¥ {{ order.transactionAmount }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="actions">
              <el-button type="primary" size="small" @click="viewOrderDetails(order.orderNumber)">订单详情</el-button>
              <el-button type="success" size="small" @click="openPayDialog(order)">去支付</el-button>
            </el-col>
          </el-row>
        </el-list>
      </el-tab-pane>

      <!-- 已付款 -->
      <el-tab-pane label="已付款" name="completed">
        <el-skeleton v-if="loadingCompleted" animated />
        <div v-else-if="completedOrders?.length === 0" class="empty-message">暂无已付款订单</div>
        <el-list
            v-for="order in completedOrders"
            :key="order.orderNumber"
            class="order-item"
            v-else
        >
          <el-row>
            <el-col :span="18">
              <h3>{{ order.stationName }} {{ order.pileCode }}</h3>
              <p>订单号: {{ order.orderNumber }}</p>
              <p>充电状态: {{ order.chargingStatus }}</p>
            </el-col>
            <el-col :span="6" class="price">
              支付金额: ¥ {{ order.transactionAmount }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="actions">
              <el-button type="primary" size="small" @click="viewOrderDetails(order.orderNumber)">查看详情</el-button>
              <el-button type="danger" size="small" @click="openRefundDialog(order)">申请退款</el-button>
            </el-col>
          </el-row>
        </el-list>
      </el-tab-pane>

      <!-- 退款/售后 -->
      <el-tab-pane label="退款/售后" name="refund">
        <el-skeleton v-if="loadingRefund" animated />
        <div v-else-if="refundOrders?.length === 0" class="empty-message">暂无退款/售后订单</div>
        <el-list
            v-for="order in refundOrders"
            :key="order.orderNumber"
            class="order-item"
            v-else
        >
          <el-row>
            <el-col :span="18">
              <h3>{{ order.stationName }} {{ order.pileCode }}</h3>
              <p>订单号: {{ order.orderNumber }}</p>
              <p>充电状态: {{ order.status }}</p>
              <p>退款状态: {{ getRefundStatusText(order.refundStatus) }}</p>
              <p v-if="order.refundAmount">退款金额: ¥ {{ order.refundAmount }}</p>
              <p v-if="order.processDescription">处理说明: {{ order.processDescription }}</p>
            </el-col>
            <el-col :span="6" class="price">
              支付金额: ¥ {{ order.amount }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" class="actions">
              <el-button type="primary" size="small" @click="viewOrderDetails(order.orderNumber)">查看详情</el-button>
              <el-button
                  v-if="order.refundStatus === 1"
                  type="warning"
                  size="small"
                  disabled
              >
                退款处理中
              </el-button>
              <el-button
                  v-if="order.refundStatus === 2"
                  type="success"
                  size="small"
                  disabled
              >
                已退款
              </el-button>
            </el-col>
          </el-row>
        </el-list>
      </el-tab-pane>
    </el-tabs>

    <!-- 支付方式弹窗 -->
    <el-dialog
        title="选择支付方式"
        v-model="payDialogVisible"
        width="400px"
        @close="resetPayDialog"
    >
      <el-form :model="payForm" label-width="200px">
        <el-form-item label="支付方式">
          <el-radio-group v-model="payForm.paymentMethodId">
            <el-radio
                v-for="method in paymentMethods"
                :key="method.id"
                :label="method.id"
            >
              {{ method.paymentMethodName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="payDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPayment">确认支付</el-button>
      </template>
    </el-dialog>

    <!-- 退款弹窗 -->
    <el-dialog
        title="申请退款"
        v-model="refundDialogVisible"
        width="400px"
        @close="resetRefundDialog"
    >
      <el-form :model="refundForm" label-width="80px">
        <el-form-item label="退款金额">
          <el-input v-model="refundForm.refundAmount" placeholder="请输入退款金额" type="number" />
        </el-form-item>
        <el-form-item label="退款理由">
          <el-input
              v-model="refundForm.refundDescription"
              placeholder="请输入退款理由"
              type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRefund">提交</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import axios from "axios";

export default {
  name: "OrderList",
  setup() {
    const activeTab = ref("pending");
    const pendingOrders = ref([]);
    const completedOrders = ref([]);
    const refundOrders = ref([]);
    const loadingPending = ref(false);
    const loadingCompleted = ref(false);
    const loadingRefund = ref(false);

    const payDialogVisible = ref(false);
    const refundDialogVisible = ref(false);

    const payForm = reactive({
      orderNumber: "",
      paymentMethodId: null,
    });

    const refundForm = reactive({
      orderNumber: "",
      refundAmount: "",
      refundDescription: "",
    });

    const paymentMethods = ref([]);

    // 获取订单和支付方式
    const fetchPendingOrders = async () => {
      loadingPending.value = true;
      try {
        const response = await axios.get("/transaction/pending", {
          params: {customerId: 1},
        });
        pendingOrders.value = response.data || [];
      } catch (error) {
        ElMessage.error("获取待付款订单失败");
      } finally {
        loadingPending.value = false;
      }
    };

    const fetchCompletedOrders = async () => {
      loadingCompleted.value = true;
      try {
        const response = await axios.get("/transaction/completed", {
          params: {customerId: 1},
        });
        completedOrders.value = response.data || [];
      } catch (error) {
        ElMessage.error("获取已付款订单失败");
      } finally {
        loadingCompleted.value = false;
      }
    };

    const fetchRefundOrders = async () => {
      loadingRefund.value = true;
      try {
        const response = await axios.get("/charging/refunds", {
          params: {customerId: 1},
        });
        refundOrders.value = response.data || [];
      } catch (error) {
        ElMessage.error("获取退款订单失败");
      } finally {
        loadingRefund.value = false;
      }
    };

    const fetchPaymentMethods = async () => {
      try {
        const response = await axios.get("/payment/methods");
        paymentMethods.value = response.data || [];
      } catch (error) {
        ElMessage.error("获取支付方式失败");
      }
    };

    // 支付功能
    const openPayDialog = (order) => {
      payForm.orderNumber = order.orderNumber;
      payForm.paymentMethodId = null;
      payDialogVisible.value = true;
    };

    const submitPayment = async () => {
      if (!payForm.paymentMethodId) {
        ElMessage.warning("请选择支付方式");
        return;
      }
      try {
        const response = await axios.post(`/transaction/pay/${payForm.orderNumber}`, {
          paymentMethodId: payForm.paymentMethodId,
        });
        if (response.data.success) {
          ElMessage.success("支付成功");
          payDialogVisible.value = false;
          fetchPendingOrders();
        } else {
          ElMessage.error("支付失败：" + response.data.message);
        }
      } catch (error) {
        ElMessage.error("支付失败");
      }
    };

    // 退款功能
    const openRefundDialog = (order) => {
      refundForm.orderNumber = order.orderNumber;
      refundForm.refundAmount = order.transactionAmount;
      refundDialogVisible.value = true;
    };

    const submitRefund = async () => {
      try {
        const response = await axios.post("/charging/refund", {
          orderNumber: refundForm.orderNumber,
          refundAmount: refundForm.refundAmount,
          refundDescription: refundForm.refundDescription,
        });
        if (response.data.success) {
          ElMessage.success("退款申请成功");
          refundDialogVisible.value = false;
          fetchCompletedOrders();
          fetchRefundOrders();
        } else {
          ElMessage.error("退款申请失败：" + response.data.message);
        }
      } catch (error) {
        ElMessage.error("退款申请失败");
      }
    };

    const resetPayDialog = () => {
      payForm.orderNumber = "";
      payForm.paymentMethodId = null;
    };

    const resetRefundDialog = () => {
      refundForm.orderNumber = "";
      refundForm.refundAmount = "";
      refundForm.refundDescription = "";
    };

    const getRefundStatusText = (status) => {
      switch (status) {
        case 0:
          return "未申请退款";
        case 1:
          return "退款处理中";
        case 2:
          return "退款成功";
        default:
          return "未知状态";
      }
    };

    onMounted(() => {
      fetchPendingOrders();
      fetchCompletedOrders();
      fetchRefundOrders();
      fetchPaymentMethods();
    });

    return {
      activeTab,
      pendingOrders,
      completedOrders,
      refundOrders,
      loadingPending,
      loadingCompleted,
      loadingRefund,
      payDialogVisible,
      refundDialogVisible,
      payForm,
      refundForm,
      paymentMethods,
      openPayDialog,
      submitPayment,
      resetPayDialog,
      openRefundDialog,
      submitRefund,
      resetRefundDialog,
      getRefundStatusText,
    };
  },
};
</script>

<style scoped>
.order-item {
  margin: 10px 0;
  padding: 10px;
  border-bottom: 1px solid #eaeaea;
}

.price {
  text-align: right;
  font-weight: bold;
}

.actions {
  margin-top: 10px;
  text-align: right;
}

.empty-message {
  text-align: center;
  margin: 20px 0;
  color: #999;
}
</style>
